import { requestUrl, RequestUrlParam } from 'obsidian';
import { DocumentShareSettings, ApiResponse, UploadDocumentRequest, UpdateDocumentRequest, Document } from './types';

export class ApiClient {
    constructor(private settings: DocumentShareSettings) {}

    private async request<T>(endpoint: string, options: Partial<RequestUrlParam> = {}): Promise<ApiResponse<T>> {
        const url = `${this.settings.apiUrl}${endpoint}`;

        try {
            const response = await requestUrl({
                url,
                method: options.method || 'GET',
                headers: {
                    'Authorization': `Bearer ${this.settings.apiToken}`,
                    'Content-Type': 'application/json',
                    'Accept': 'application/json',
                    ...options.headers,
                },
                body: options.body,
                throw: false,
            });

            // 检查响应的 Content-Type
            const contentType = response.headers['content-type'] || response.headers['Content-Type'] || '';

            // 如果不是 JSON 响应，说明可能是错误页面
            if (!contentType.includes('application/json')) {
                return {
                    success: false,
                    error: 'API 返回了非 JSON 响应',
                    message: `请检查 API 地址配置是否正确。当前配置: ${this.settings.apiUrl}\n响应状态码: ${response.status}\nContent-Type: ${contentType}`,
                };
            }

            // 尝试解析 JSON
            try {
                return response.json;
            } catch (parseError) {
                return {
                    success: false,
                    error: 'JSON 解析失败',
                    message: `服务器返回了无效的 JSON 数据。响应状态码: ${response.status}`,
                };
            }
        } catch (error) {
            return {
                success: false,
                error: '网络请求失败',
                message: `${error.message}\n请检查:\n1. API 地址是否正确\n2. 服务器是否正在运行\n3. 网络连接是否正常`,
            };
        }
    }

    // 上传文档
    async uploadDocument(data: UploadDocumentRequest): Promise<ApiResponse<Document>> {
        return this.request<Document>('/documents', {
            method: 'POST',
            body: JSON.stringify(data),
        });
    }

    // 获取文档列表
    async getDocuments(): Promise<ApiResponse<Document[]>> {
        return this.request<Document[]>('/documents');
    }

    // 获取单个文档
    async getDocument(uuid: string): Promise<ApiResponse<Document>> {
        return this.request<Document>(`/documents/${uuid}`);
    }

    // 更新文档
    async updateDocument(uuid: string, data: UpdateDocumentRequest): Promise<ApiResponse<Document>> {
        return this.request<Document>(`/documents/${uuid}`, {
            method: 'PUT',
            body: JSON.stringify(data),
        });
    }

    // 删除文档
    async deleteDocument(uuid: string): Promise<ApiResponse> {
        return this.request(`/documents/${uuid}`, {
            method: 'DELETE',
        });
    }

    // 轮换 Token
    async rotateToken(): Promise<ApiResponse<{ token: string }>> {
        return this.request<{ token: string }>('/token/rotate', {
            method: 'POST',
        });
    }

    // 测试连接
    async testConnection(): Promise<boolean> {
        const response = await this.getDocuments();
        return response.success;
    }

    // 获取文档查看 URL (从 API URL 推断 web URL)
    getDocumentViewUrl(uuid: string): string {
        // 从 https://your-domain.com/api 得到 https://your-domain.com
        const baseUrl = this.settings.apiUrl.replace(/\/api\/?$/, '');
        return `${baseUrl}/d/${uuid}`;
    }
}
